<?php

namespace app\api\controller;

use app\h5\service\PayService;
use think\facade\Cache;
use think\facade\Request;
use app\api\service\FastAppService;
use app\common\Common;
use app\common\Error;
use app\BaseController;

class FastApp extends BaseController
{
    private $service;
    private $payService;

    public function __construct(FastAppService $service, PayService $payService)
    {
        $this->service = $service;
        $this->payService = $payService;
    }

    // 登录
    public function login()
    {
        $params = Request::param();

        try {
            validate(\app\api\validate\Login::class)->scene('fast_app_login')->check($params);
        } catch (\Exception $e) {
            return Common::fail($e->getError());
        }

        $data = $this->service->userLogin($params);

        if (empty($data)) {
            return Common::fail(Error::LOGIN_ERROR);
        }

        return Common::success($data);
    }

    //支付
    public function doPay()
    {
        $params = Request::param();
        flog([
            'message' => '快应用支付请求参数',
            'params' => $params,
        ],'quick_app_pay');
        $params['source'] = $this->payService::SOURCE_QUICK_APP;
        try {
            validate(\app\api\validate\Pay::class)->scene('doPay')->check($params);

            $data = $this->payService->doPay($params, $this->getUserID());
            if (!empty($data['message'])) {
                return Common::fail($data['message']);
            }
            return Common::success($data);
        } catch (\Exception $e) {
            flog([
                'message' => $e->getMessage(),
                'params' => $params,
            ],'quick_app_pay','error');
            return Common::fail($e->getMessage());
        }
    }

    /**
     * 获取用户id
     * @return mixed
     */
    public function getUserID()
    {
        $header = Request::header();
        $redis = Cache::store('redis')->handler();
        $redis->select(8);
        return $redis->get($header['token']);
    }
}